package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.*;
import com.basic.modules.nykf.dao.ConsultationRecordsDao;
import com.basic.modules.nykf.dao.ConsultationRecordsGjDao;
import com.basic.modules.nykf.entity.ConsultationRecordsEntity;
import com.basic.modules.nykf.entity.ConsultationRecordsGjEntity;
import com.basic.modules.nykf.entity.FileNewEntity;
import com.basic.modules.nykf.service.ConsultationRecordsGjService;
import com.basic.modules.nykf.service.ConsultationRecordsService;
import com.basic.modules.nykf.service.CustomerService;
import com.basic.modules.nykf.service.FileNewService;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service("consultationRecordsService")
public class ConsultationRecordsServiceImpl extends ServiceImpl<ConsultationRecordsDao, ConsultationRecordsEntity> implements ConsultationRecordsService {

    @Autowired
    CustomerService customerService;

    @Autowired
    ConsultationRecordsGjService consultationRecordsGjService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    ConsultationRecordsGjDao consultationRecordsGjDao;

    @Autowired
    FileNewService fileNewService;

    @Override
    public PageUtils getConsultationRecordsList(ParamsModel<ConsultationRecordsEntity> params) {
        IPage<ConsultationRecordsEntity> page = new Query<ConsultationRecordsEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<ConsultationRecordsEntity> customerList = baseMapper.getConsultationRecordsList(page, params.getCondition());
        return new PageUtils(customerList);
    }

    @Override
    public R addConsultationRecords(ConsultationRecordsEntity consultationRecordsEntity) {
        // 去空格
        String zxkhmc = consultationRecordsEntity.getZxkhmc();
        if (zxkhmc != null) {
            zxkhmc = zxkhmc.replace(" ", "");
        }
        String zxdpmc = consultationRecordsEntity.getZxdpmc();
        if (zxdpmc != null) {
            zxdpmc = zxdpmc.replace(" ", "");
        }
        consultationRecordsEntity.setZxkhmc(zxkhmc);
        consultationRecordsEntity.setZxdpmc(zxdpmc);

        R inspect = null;
        // 校验
        if (consultationRecordsEntity.getZxid() == null) {
            Object object = SecurityUtils.getSubject().getPrincipal();
            SysUserEntity sysUser = (SysUserEntity) object;
            consultationRecordsEntity.setCreateUserId(sysUser.getUserId());
            consultationRecordsEntity.setCreateTime(DateUtil.date());
            inspect = inspectAddOrEdit(consultationRecordsEntity, "add");
        } else {
            inspect = inspectAddOrEdit(consultationRecordsEntity, "edit");
        }
        if (inspect.get("code").equals(500)) {
            return inspect;
        }

        // 计算填充率
        double tcl = ConsultationRecordsGjServiceImpl.calculateFillRate(consultationRecordsEntity);
        consultationRecordsEntity.setTcl(tcl);
        if (consultationRecordsEntity.getZxid() == null) {
            // 保存咨询表
            this.save(consultationRecordsEntity);
            // 保存跟进记录表
            ConsultationRecordsGjEntity consultationRecordsGjEntity = new ConsultationRecordsGjEntity();
            consultationRecordsGjEntity.setDqjdVal(consultationRecordsEntity.getDqjdVal());
            consultationRecordsGjEntity.setDqjdName(consultationRecordsEntity.getDqjdName());
            consultationRecordsGjEntity.setGjfsVal(consultationRecordsEntity.getGjfsVal());
            consultationRecordsGjEntity.setGjfsName(consultationRecordsEntity.getGjfsName());
            consultationRecordsGjEntity.setXcgjsj(consultationRecordsEntity.getXcgjsj());
            consultationRecordsGjEntity.setGjsj(new Date());
            consultationRecordsGjEntity.setZxid(consultationRecordsEntity.getZxid());
            consultationRecordsGjService.saveData(consultationRecordsGjEntity);

            Long gjjlId = consultationRecordsGjEntity.getGjjlId();
            // 切割附件
            if (consultationRecordsEntity.getFileIds() != null && !"".equals(consultationRecordsEntity.getFileIds())) {
                consultationRecordsEntity.setFileIds(consultationRecordsEntity.getFileIds().substring(1));
                String fileIds = consultationRecordsEntity.getFileIds();
                String[] fileIdsArray = fileIds.split(",");
                for (String id : fileIdsArray) {
                    UpdateWrapper<FileNewEntity> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.lambda()
                            .eq(FileNewEntity::getYkfFileId, id)
                            .set(FileNewEntity::getGlId, gjjlId);
                    fileNewService.update(updateWrapper);
                }
            }
            return R.ok(consultationRecordsGjEntity);
        } else {
            this.updateById(consultationRecordsEntity);
        }
        return R.ok();
    }

    public R inspectAddOrEdit(ConsultationRecordsEntity consultationRecordsEntity, String type) {

        // 咨询客户名称不允许重复
        QueryWrapper<ConsultationRecordsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("zxkhmc", consultationRecordsEntity.getZxkhmc());
        if ("edit".equals(type)) {
            queryWrapper.ne("zxid", consultationRecordsEntity.getZxid());
        }
        int count = this.count(queryWrapper);
        if (count > 0) {
            return R.error("咨询客户名称");
        }

        // 同平台店铺名称禁止重复
        String ZxdpptVal = consultationRecordsEntity.getZxdpptVal();
        String Zxdpmc = consultationRecordsEntity.getZxdpmc();
        QueryWrapper<ConsultationRecordsEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("zxdppt_val", ZxdpptVal);
        queryWrapper1.eq("zxdpmc", Zxdpmc);
        if ("edit".equals(type)) {
            queryWrapper1.ne("zxid", consultationRecordsEntity.getZxid());
        }
        int count1 = this.count(queryWrapper1);
        if (count1 > 0) {
            return R.error("已存在同平台相同名称的店铺！");
        }
        return R.ok();
    }

    @Override
    public List<ConsultationRecordsGjEntity> getGjListByZxId(ConsultationRecordsEntity consultationRecordsEntity) {
        Long zxid = consultationRecordsEntity.getZxid();
        ConsultationRecordsGjEntity consultationRecordsGjEntity = new ConsultationRecordsGjEntity();
        consultationRecordsGjEntity.setZxid(zxid);
        List<ConsultationRecordsGjEntity> consultationGjjlList = consultationRecordsGjDao.getConsultationGjjlList(0, 9999, consultationRecordsGjEntity);
        for (int i = consultationGjjlList.size() - 1; i >= 0; i--) {
            // 每次跟进记录的跟进时间跟上次的跟记录的下次跟进时间做对比，超过24小时则视为超时跟进
            if (i == consultationGjjlList.size() - 1) {
                continue;
            }
            // 上一次
            ConsultationRecordsGjEntity syc = consultationGjjlList.get(i + 1);
            Date xcgjsj = syc.getXcgjsj();
            // 本次
            ConsultationRecordsGjEntity bc = consultationGjjlList.get(i);
            Date gjsj = bc.getGjsj();

            // 超过24小时则视为超时
            // 计算时间差（毫秒）
            long timeDifference = gjsj.getTime() - xcgjsj.getTime();
            // 24小时对应的毫秒数
            long twentyFourHoursInMillis = 24 * 60 * 60 * 1000;

            // 如果时间差超过24小时，则设置超时标志
            bc.setTimeoutFlag(timeDifference > twentyFourHoursInMillis);
        }
        return consultationGjjlList;
    }

    @Override
    public List<Map<String, Object>> getZxjlKbData(Map<String, Object> map) {
        List<Map<String, Object>> zxjlKbData;
        String startDate;
        String endDate;

        if (map.get("dataRange") != null) {
            String dataRange = map.get("dataRange").toString();
            if ("customize".equals(dataRange)) {
                startDate = map.get("startDate").toString();
                endDate = map.get("endDate").toString();
            } else {
                startDate = DateUtils.getFirstDayOfRange(dataRange);
                endDate = DateUtils.format(new Date());
            }
            zxjlKbData = baseMapper.getZxjlKbData(startDate, endDate);
        } else {
            zxjlKbData = baseMapper.getZxjlKbData(null, null);
        }

        BigDecimal dqzx = BigDecimal.ZERO;
        BigDecimal yxzx = BigDecimal.ZERO;

        for (Map<String, Object> record : zxjlKbData) {
            String dataType = record.get("dataType").toString();
            if ("dqzx".equals(dataType)) {
                dqzx = new BigDecimal(record.get("zhi").toString());
            } else if ("yxzx".equals(dataType)) {
                yxzx = new BigDecimal(record.get("zhi").toString());
            }
        }

        BigDecimal zxyxl = BigDecimal.ZERO;
        if (dqzx.compareTo(BigDecimal.ZERO) != 0) {
            zxyxl = yxzx.divide(dqzx, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
        }

        Map<String, Object> resultEntry = new HashMap<>();
        resultEntry.put("dataType", "zxyxl");
        resultEntry.put("zhi", zxyxl);
        resultEntry.put("displayValue", zxyxl + "%");
        zxjlKbData.add(resultEntry);

        return zxjlKbData;
    }

    @Override
    public List<Map<String, Object>> getZxjlZztData() {
        return baseMapper.getZxjlZztData();
    }

    @Override
    public List<Map<String, Object>> getCalendarDgjjls(Map map) {
        map.put("minDate", map.get("year") + "-" + map.get("month") + "-01");
        // 每日待跟进的数量(咨询表)
        List<Map<String, Object>> calendarDgjjls = baseMapper.getCalendarDgjjls(map);
        return calendarDgjjls;
    }
}